package com.example.idachuappone.person.item;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.baidu.location.BDLocation;
import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.promptly.entity.UserInfo;
import com.example.idachuappone.utils.AppShareData;
import com.example.idachuappone.utils.CheckUtil;
import com.example.idachuappone.utils.ComUtil;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class LoginActivity extends BaseActivity implements OnClickListener {
	private String auth;
	private Button btn_back;
	private Button btn_getSmsCode;
	private Button btn_next;
	private Dialog cusProDialog;
	private boolean doTimeCal;
	private EditText edit_inputPhone;
	private EditText edit_inputSmsCode;
	private boolean flag;
	private Handler handler;
	private boolean isLogin;
	private String phone;
	private String smsCode;
	private String uid;
	private String uphone;
	private UserInfo userInfo;

	class AnonymousClass_4 extends RequestCallBack<String> {
		private final/* synthetic */String val$strPhone;

		AnonymousClass_4(String str) {
			this.val$strPhone = str;
		}

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			AppShareData.isPersonFrag = true;
			PrefUtil.getInstance(LoginActivity.this).setLoginPhone(this.val$strPhone);
			LoginActivity.this.parseRegResult(NetUtil.unescapeUnicode(responseInfo.result));
		}

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			LoginActivity.this.cusProDialog.dismiss();
			MainToast.show(LoginActivity.this, "\u767b\u5f55\u5931\u8d25\uff0c\u8bf7\u91cd\u65b0\u64cd\u4f5c", 0);
		}
	}

	public LoginActivity() {
		this.flag = false;
		this.smsCode = "err";
		this.doTimeCal = false;
		this.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case BDLocation.TypeNone /* 0 */:
					LoginActivity.this.btn_getSmsCode.setText(msg.arg1 + "s");
				case 1 /* 1 */:
					LoginActivity.this.btn_getSmsCode.setEnabled(true);
					LoginActivity.this.btn_getSmsCode.setText("\u9a8c\u8bc1");
					if (LoginActivity.this.edit_inputPhone.getText().toString().length() == 11) {
						LoginActivity.this.btn_getSmsCode.setEnabled(true);
					} else {
						LoginActivity.this.btn_getSmsCode.setEnabled(false);
					}
				default:
				}
			}
		};
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		this.isLogin = getIntent().getBooleanExtra("islogin", false);
		initView();
	}

	private void initView() {
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.cusProDialog = ComUtil.createCusProgressSmallBlackBgDialog(this);
		this.cusProDialog.setCancelable(false);
		this.btn_getSmsCode = (Button) findViewById(R.id.btn_getsmscode);
		this.btn_getSmsCode.setOnClickListener(this);
		this.btn_next = (Button) findViewById(R.id.btn_next);
		this.btn_next.setOnClickListener(this);
		this.edit_inputSmsCode = (EditText) findViewById(R.id.edit_inputSmsCode);
		this.edit_inputSmsCode.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (LoginActivity.this.edit_inputSmsCode.getText().toString().length() <= 0
						|| LoginActivity.this.edit_inputPhone.getText().toString().length() != 11) {
					LoginActivity.this.btn_next.setEnabled(false);
				} else {
					LoginActivity.this.btn_next.setEnabled(true);
				}
			}
		});
		this.edit_inputPhone = (EditText) findViewById(R.id.edit_inputphone);
		this.edit_inputPhone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				LoginActivity.this.btn_getSmsCode.setText("\u9a8c\u8bc1");
				LoginActivity.this.doTimeCal = false;
				if (LoginActivity.this.edit_inputSmsCode.getText().toString().length() <= 0
						|| LoginActivity.this.edit_inputPhone.getText().toString().length() != 11) {
					LoginActivity.this.btn_next.setEnabled(false);
				} else {
					LoginActivity.this.btn_next.setEnabled(true);
				}
				if (LoginActivity.this.edit_inputPhone.getText().toString().length() == 11) {
					LoginActivity.this.btn_getSmsCode.setEnabled(true);
				} else {
					LoginActivity.this.btn_getSmsCode.setEnabled(false);
				}
			}
		});
	}

	private void smsLogin(String strPhone, String code) {
		Map<String, String> map = new HashMap();
		map.put("phone", strPhone);
		map.put("code", code);
		NetUtil.post(this, Constant.SMS_CODE_LOGIN, map, new AnonymousClass_4(strPhone));
	}

	private void parseRegResult(String strJson) {
		try {
			JSONObject object = new JSONObject(strJson);
			String regResult = object.optString("code");
			if ("10000".equals(regResult)) {
				this.uid = object.getJSONObject("data").getJSONObject("user").getString("uid");
				this.auth = object.getJSONObject("data").getString("auth");
				this.uphone = object.getJSONObject("data").getJSONObject("user").optString("phone");
				PrefUtil.getInstance(this).setUID(this.uid);
				PrefUtil.getInstance(this).setAuth(this.auth);
				initDate();
			} else if (Integer.parseInt(regResult) == 300) {
				this.cusProDialog.dismiss();
				MainToast.show(this, object.optString("error"), 0);
			}
		} catch (JSONException e) {
			this.cusProDialog.dismiss();
			MainToast.show(this, "\u767b\u5f55\u5931\u8d25\uff0c\u8bf7\u91cd\u65b0\u64cd\u4f5c", 0);
		}
	}

	private void initDate() {
		NetUtil.get(this, Constant.USER_INFO, 100, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					LoginActivity.this.cusProDialog.dismiss();
					JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
					if (jsonObject.getInt("code") == 10000) {
						LoginActivity.this.userInfo = new UserInfo();
						LoginActivity.this.userInfo.parseJson(jsonObject.getJSONObject("data"));
						PrefUtil prefUtil;
						if (LoginActivity.this.userInfo.getAddresses() == null
								|| LoginActivity.this.userInfo.getAddresses().size() <= 0) {
							prefUtil = PrefUtil.getInstance(LoginActivity.this);
							prefUtil.setUID(LoginActivity.this.uid);
							prefUtil.setAuth(LoginActivity.this.auth);
							prefUtil.setPhone(LoginActivity.this.uphone);
						} else {
							prefUtil = PrefUtil.getInstance(LoginActivity.this);
							prefUtil.setUID(LoginActivity.this.uid);
							prefUtil.setAuth(LoginActivity.this.auth);
							prefUtil.setPhone(LoginActivity.this.uphone);
							prefUtil.setFimallyLocateCoor(new StringBuilder(String.valueOf(LoginActivity.this.userInfo
									.getAddresses().get(0).getLng())).append(",")
									.append(LoginActivity.this.userInfo.getAddresses().get(0).getLat()).toString());
							prefUtil.setArea(LoginActivity.this.userInfo.getAddresses().get(0).getArea());
							prefUtil.setXiaoQu(LoginActivity.this.userInfo.getAddresses().get(0).getCommunity());
							prefUtil.setDoor(LoginActivity.this.userInfo.getAddresses().get(0).getDoor_number());
							prefUtil.setName(LoginActivity.this.userInfo.getAddresses().get(0).getName());
							prefUtil.setUserAddressId(LoginActivity.this.userInfo.getAddresses().get(0).getId());
							prefUtil.setPhone(LoginActivity.this.userInfo.getAddresses().get(0).getPhone());
						}
						AppShareData.isRefreshOrderAll = true;
						AppShareData.isRefreshOrderPay = true;
						AppShareData.isRefreshOrderComment = true;
						MainToast.show(LoginActivity.this, "\u767b\u5f55\u6210\u529f\uff01", 0);
						LoginActivity.this.setResult(-1);
						LoginActivity.this.finish();
						return;
					}
					MainToast.show(LoginActivity.this, jsonObject.getString("error"), 0);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				NetUtil.netFail(LoginActivity.this, LoginActivity.this.cusProDialog, true);
			}
		});
	}

	private void parseSmsCode(String s) {
		try {
			JSONObject obj = new JSONObject(s);
			String errCode = obj.optString("code");
			if ("10000".equals(errCode)) {
				this.smsCode = obj.optString("verifycode");
				this.cusProDialog.dismiss();
				MainToast
						.show(this,
								"\u9a8c\u8bc1\u7801\u5df2\u53d1\u9001\u81f3\u60a8\u624b\u673a\uff0c\u8bf7\u6ce8\u610f\u67e5\u6536",
								1);
				this.flag = true;
				calTime();
			} else if (Integer.parseInt(errCode) == 300) {
				this.cusProDialog.dismiss();
				MainToast.show(this, obj.optString("error"), 0);
			}
		} catch (JSONException e) {
			this.cusProDialog.dismiss();
			MainToast.show(this, "\u83b7\u53d6\u9a8c\u8bc1\u7801\u5931\u8d25\uff0c\u8bf7\u91cd\u65b0\u64cd\u4f5c", 0);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.doTimeCal = false;
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			doJudgeBack();
		case R.id.btn_getsmscode /* 2131165324 */:
			this.phone = this.edit_inputPhone.getText().toString().trim();
			if (this.phone == null || "".equals(this.phone)) {
				MainToast.show(this, "\u8bf7\u8f93\u5165\u624b\u673a\u53f7", 0);
			} else if (!CheckUtil.isCellphone(this.phone)) {
				MainToast.show(this, "\u8bf6\uff0c\u624b\u673a\u53f7\u586b\u9519\u4e86\u5462~", 0);
			} else if (CheckUtil.checkNet(this)) {
				this.cusProDialog.show();
				getSmsCode(this.phone);
			} else {
				MainToast.show(this, getResources().getString(R.string.txt_network), 0);
			}
		case R.id.btn_next /* 2131165326 */:
			this.phone = this.edit_inputPhone.getText().toString().trim();
			if (this.phone == null || "".equals(this.phone)) {
				MainToast.show(this, "\u8bf7\u8f93\u5165\u624b\u673a\u53f7", 0);
			} else if (CheckUtil.isCellphone(this.phone)) {
				String inputCode = this.edit_inputSmsCode.getText().toString().trim();
				if (inputCode == null || "".equals(inputCode)) {
					MainToast.show(this, "\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801", 0);
				} else if (CheckUtil.checkNet(this)) {
					this.cusProDialog.show();
					smsLogin(this.phone, inputCode);
				} else {
					MainToast.show(this, getResources().getString(R.string.txt_network), 0);
				}
			} else {
				MainToast.show(this, "\u8bf6\uff0c\u624b\u673a\u53f7\u586b\u9519\u4e86\u5462~", 0);
			}
		default:
		}
	}

	private void calTime() {
		this.doTimeCal = true;
		this.btn_getSmsCode.setEnabled(false);
		new Thread() {
			@Override
			public void run() {
				int i = 60;
				while (i >= 0 && LoginActivity.this.doTimeCal) {
					Message msg = LoginActivity.this.handler.obtainMessage(0);
					msg.arg1 = i;
					LoginActivity.this.handler.sendMessage(msg);
					i--;
					SystemClock.sleep(1000);
				}
				LoginActivity.this.handler.sendEmptyMessage(1);
			}
		}.start();
	}

	private void getSmsCode(String strPhone) {
		Map<String, String> map = new HashMap();
		map.put("phone", strPhone);
		NetUtil.post(this, Constant.GET_SMS_CODE, map, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				if (responseInfo.result != null) {
					LoginActivity.this.parseSmsCode(NetUtil.unescapeUnicode(responseInfo.result));
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				LoginActivity.this.cusProDialog.dismiss();
				MainToast.show(LoginActivity.this,
						"\u7f51\u7edc\u4e0d\u7ed9\u529b\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5\u3002", 0);
			}
		});
	}

	public void doJudgeBack() {
		if (this.flag) {
			new Builder(this)
					.setTitle("\u6ce8\u610f")
					.setMessage(
							"\u7a0d\u7b49\u4e00\u4e0b\uff0c\u9a8c\u8bc1\u7801\u5f88\u5feb\u5c31\u5230\u3002\u786e\u5b9a\u8981\u653e\u5f03\u767b\u5f55\u5417\uff1f")
					.setPositiveButton("\u4e0d\u7b49\u4e86", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							LoginActivity.this.finish();
						}
					}).setNegativeButton("\u518d\u7b49\u7b49", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					}).setCancelable(false).show();
		} else {
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 4) {
			doJudgeBack();
		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == -1) {
			setResult(-1);
			finish();
		}
	}
}
